import { useEffect, useRef } from "react";
import {
    ArcRotateCamera, Color4, Engine, HemisphericLight, Mesh, MeshBuilder, Plane, Scene, Vector3
} from '@babylonjs/core';


const canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;


const engine = new Engine(canvas, true);
const scene = new Scene(engine);



const camera = new ArcRotateCamera('Camera', Math.PI / 3, Math.PI / 3, 9, new Vector3(0, 0, 0), scene);
camera.attachControl(canvas, true);


const light = new HemisphericLight('pxg', new Vector3(1, 1, 0), scene);
const ground = MeshBuilder.CreateGround('ground', { width: 10, height: 10, updatable: true }, scene);
const updateAction: ((time: number) => {})[] = [];


const box = MeshBuilder.CreateBox('box', {
    sideOrientation: Mesh.FRONTSIDE,
    faceColors: [
        new Color4(1, 0, 0, 1),
        new Color4(0, 1, 0, 1),
        new Color4(0, 0, 1, 1),
        new Color4(1, 0, 0, 1),
        new Color4(0, 1, 0, 1),
        new Color4(0, 0, 1, 1),
    ]
}, scene);
box.position.set(0, 1.5, 0);

const lineVertices = [
    new Vector3(1, 0, 1),
    new Vector3(-1, 0, 1),
    new Vector3(-1, 0, -1),
    new Vector3(1, 0, -1),
    new Vector3(1, 0, 1),
];
const lines = MeshBuilder.CreateLines('line', { points: lineVertices }, scene);
box.addChild(lines);



updateAction.push((time) => {
    const angle = Math.sin(time / 200) * 0.1;
    lines.position.y = angle;
    const scalAngle = 1 + angle * 0.4;
    lines.scaling.set(scalAngle, scalAngle, scalAngle);
    return '';
});




const RenderStructure = () => {
    const divRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        const { current } = divRef;
        if (current != null) {
            current.innerHTML = '';
            current.append(canvas);
            ani(0);
        }
    }, []);
    return (
        <div ref={divRef}></div>
    );
};

export default RenderStructure;

function ani(time: number) {
    updateAction.forEach((action) => {
        action(time);
    })
    scene.render();

    requestAnimationFrame(ani);
}